package com.alan.nio.chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * Created by Alan on 2017/8/5.
 */
public class Server {

    public static void main(String[] args) throws IOException {

        //1.获取通道
        ServerSocketChannel channel = ServerSocketChannel.open();

        //2.切换到非阻塞模式
        channel.configureBlocking(false);

        //3.绑定端口
        channel.bind(new InetSocketAddress(9999));

        //4.获取选择器
        Selector selector = Selector.open();

        //5.将通道注册到选择器上
        channel.register(selector, SelectionKey.OP_ACCEPT);

        //6.轮询
        while (selector.select() > 0){
            //7.获取选择器上的所有选项
            Iterator<SelectionKey> it = selector.selectedKeys().iterator();
            while (it.hasNext()){
                //8.获取就绪事件
                System.out.println("------tt----");
                SelectionKey key = it.next();
                //9.判断获取到的是什么事件
                if(key.isAcceptable()){
                    //10.如果是可接受就绪
                    System.out.println("--------isAcceptable-------");
                    SocketChannel sc = channel.accept();

                    sc.configureBlocking(false);

                    sc.register(selector,SelectionKey.OP_READ );

                }else if(key.isReadable()){
                    System.out.println("--------isReadable-------");
                    //如果是读就绪
                    SocketChannel channel2 = (SocketChannel) key.channel();

                    //读取
                    ByteBuffer buffer = ByteBuffer.allocate(1024);

                    int len;
                    while ((len = channel2.read(buffer)) > 0){
                        buffer.flip();
                        System.out.println(new String(buffer.array(),0,len));
                        buffer.clear();
                    }
                }
                it.remove();
            }
        }
        System.out.println("-----------------");
    }

}
